rm(list = ls())
load("dataBJPOLS.RData")

# --------------------------------------------------
# First stage - full sample
# --------------------------------------------------
inst.1 <- "judgeiv_hd"
endo.1 <- "pti"
outc.1 <- "vote_post"

time.controls <- "as.factor(court_time1) + as.factor(court_time2) + as.factor(court_dow) + as.factor(severity)"
demo.controls <- "age + I(age^2) +  as.factor(race4) + female + vote_pre + as.factor(noteli) + regis_before"
case.controls <- "as.factor(any_drug) +  as.factor(any_weapon) +  as.factor(any_prop) + as.factor(any_prior_case)"

form.2 <- formula(paste(inst.1, "~", time.controls))
mod1b <- lm(form.2, data = last.cases)
last.cases$judgeiv_res <- last.cases$judgeiv - predict(mod1b, last.cases)

form.1 <- formula(paste(outc.1, "~", demo.controls, "+", case.controls))
m1a1 <- lm(form.1, data = last.cases)
last.cases$pred_turn <- predict(m1a1)

mod2 <- lm(pred_turn ~ judgeiv_res, data = last.cases)

judgeiv_res <- seq(min(last.cases$judgeiv_res), max(last.cases$judgeiv_res), by = 0.01)
data.pred2 <- data.table(judgeiv_res)

myPredict <- predict(mod2, newdata = data.pred2, interval = "confidence")

pdf("./Figures/Figure_A02_BJPOLS.pdf", h=8,w=8)    
par(mar = c(6, 6, 4, 6), mgp=c(2,1,0))

hist(last.cases$judgeiv_res, 
     freq = F, breaks = 10, las = 1,
     xlab = paste0("Leave-out-case Residualized Pretrial Detention Rate"),
     main = "", ylim = c(0, 6))
x <- judgeiv_res
ix <- sort(x,index.return=T)$ix
text(0.05, 5, paste0("Correlation = ", round(cor(last.cases$judgeiv_res, last.cases$pred_turn), 3)))

par(new = T)
plot(x, myPredict[, 1], axes=F, xlab=NA, ylab=NA, type = "l", col = "red", ylim = c(0.18, 0.40))
polygon(c(rev(x[ix]), x[ix]), c(rev(myPredict[ ix,3]), myPredict[ ix,2]), col = rgb(0.7,0.7,0.7,0.4) , border = NA)
lines(x[ix], myPredict[ix , 1], col=2, lwd=2)
axis(4, at = seq(from = 0.18, to = 0.40, by = 0.01), 
     labels = seq(from = 0.18, to = 0.40, by = 0.01), 
     col = 'red', col.axis = 'red', las = 1)
mtext("Predicted Turnout Rates", side = 4, col = "red", line = 4)
dev.off()

 
